package com.zl.controller;

import com.zl.pojo.User;
import com.zl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/loginUser")
    public String loginUser(User user, String isno, HttpSession session, HttpServletResponse response) throws UnsupportedEncodingException {
        user = userService.loginUser(user);
        if(user!=null){
            if ("yes".equals(isno)) {
                Cookie nameCookie = new Cookie("name", URLEncoder.encode(user.getLoginname(), "utf-8"));
                Cookie pwdCookie = new Cookie("pwd", user.getPassword());
                // 设置Cookie时间
                nameCookie.setMaxAge(24 * 60 * 60 * 10);
                pwdCookie.setMaxAge(24 * 60 * 60 * 10);
                // 设置Cookie对应的路径
                nameCookie.setPath("/easyBuy");
                pwdCookie.setPath("/easyBuy");
                // 发送给客户端
                response.addCookie(nameCookie);
                response.addCookie(pwdCookie);
            }
            session.setAttribute("LoginUser",user);
        }else {
            return "/login.jsp?error=用户名或密码错误！";
        }
        return "/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "/login";
    }
}
